<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>聊天demo</title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<script>
			$(function(){
				//初始化socket
				initWebSocket();
			});
			var myUserName;
			//初始化WebSocket
			function initWebSocket() {
				if (!window.WebSocket) {
					window.WebSocket = window.MozWebSocket;
				}
				if (window.WebSocket) {
					socket = new WebSocket("ws://115.28.74.110:8080/WebSocketDemo/SocketServer");
					//收到消息的回调
					socket.onmessage = function() {
						handleMessage(event.data);
					};
					socket.onopen = function(event) {
						//链接开启的回调
						console.log("链接成功！");
						var msgJson = "{userId:151515}";
						console.log(msgJson);
						send(msgJson);
					};
					socket.onclose = function(event) {
						//链接关闭的回调
						console.log("链接关闭！");
					};
				} else {
					alert("你的浏览器不支持！");
				}
			}
			//处理消息
			function handleMessage(data) {
				var msgJsonData = JSON.parse(data);
				console.log(msgJsonData);
				$("#textAreaID").append(data+"<br/>");
				$("#textAreaID").scrollTop($("#textAreaID")[0].scrollHeight);
			}
			//通过socket发送消息
			function send(message) {
				if (!window.WebSocket) {
					return;
				}
				if (socket.readyState == WebSocket.OPEN) {
					socket.send(message);
				} else {
					alert("连接没有开启.");
				}
			}
			
			function setUserId (p_userName) {
				myUserName = p_userName;
				var msgJson = "{methodName:'login',userName:'"+myUserName+"'}";
				send(msgJson);
			}
			function sendAll (msg) {
				var msgJson = "{methodName:'SendAllMsg',msg:'"+msg+"',userName:'"+myUserName+"'}";
				send(msgJson);
			}
		</script>
	</head>
	<body>
		<input type="text" id="userName" />
		<button onclick="setUserId(userName.value)">设置名称并登陆</button>
		<br />
		
		
		<br />
		<!--显示消息-->
		<div id="textAreaID" style="width: 500px;height: 500px; border: 1px solid #000000;overflow:auto;">
		</div>
		<br />
		消息：<input id="chatMsgInput" />
		<button onclick="sendAll(chatMsgInput.value)">发送</button>
	</body>
</html>
